/*
 * Copyright 2014 Soichiro Kashima
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tsingteng.cosfun.ui.mine;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.tsingteng.cosfun.MainActivity;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BaseFragment;
import com.tsingteng.cosfun.bean.BaseDataBean;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.LabelBean;
import com.tsingteng.cosfun.bean.PersonBean;
import com.tsingteng.cosfun.bean.VidePersonBean;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.common.BroadcastManager;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.cosfun.ShareFragment;
import com.tsingteng.cosfun.ui.cosfun.contract.PersonCenterContract;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverListener;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverManager;
import com.tsingteng.cosfun.ui.cosfun.presenter.PersonCenterPresenter;
import com.tsingteng.cosfun.ui.message.MessageFragment;
import com.tsingteng.cosfun.ui.message.messagereport.MessageReportFragment;
import com.tsingteng.cosfun.ui.mine.tab.PersonTabListParaGraphFragment;
import com.tsingteng.cosfun.ui.mine.tab.PersonTabListVideoFragment;
import com.tsingteng.cosfun.ui.setting.HomeSettingFragment;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.DateUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.ImageViewUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.NotchUtil;
import com.tsingteng.cosfun.utils.SPUtils;
import com.tsingteng.cosfun.utils.ShareUtils;
import com.tsingteng.cosfun.utils.StringUtils;
import com.tsingteng.cosfun.widget.TopActionBar;
import com.tsingteng.cosfun.widget.dialog.BottomListDialog;
import com.tsingteng.cosfun.widget.dialog.ConfirmDialog;
import com.tsingteng.cosfun.widget.flexible.ScrollUtils;
import com.tsingteng.cosfun.widget.flexible.Scrollable;
import com.tsingteng.cosfun.widget.flexible.SlidingTabLayout;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.app.Activity.RESULT_OK;
import static com.tsingteng.cosfun.widget.TopActionBar.RIGHT_AREA;
import static com.tsingteng.cosfun.widget.TopActionBar.RIGHT_AREA2;


/**
 * author :zhikuan
 * Date:18-8-2
 */
public class HomeMineFragment extends BaseFragment implements PersonCenterContract.IPersonCenterView, View.OnClickListener, ObserverListener
        , TopActionBar.OnTopBarButtonClickListener {

    private static final String TAG = "HomeMineFragment";
    public static boolean isOutLogon = false;
    public static final String USERID = "userId";
    private ViewPager mPager;
    private NavigationAdapter mPagerAdapter;
    private SlidingTabLayout mSlidingTabLayout;
    private int mFlexibleSpaceHeight;
    private int mTabHeight;
    private int minTopMargin;
    private PersonCenterPresenter personCenterPresenter;
    private int currentId;
    private int tag;
    private String other = "other";
    private List<String> mList = new ArrayList();
    private BottomListDialog dialog;
    private TopActionBar topActionBar;
    private TextView attent, nickname, userinfo, sign, accountId;        //关注
    private View messageBg;       //消息
    private CircleImageView headView;//头像
    public String headurl = "";
    private ImageView lableImg;
    private TextView label1, label2;//关注，粉丝，赞
    private TextView countAttent, countFans, countPraise;//关注，粉丝，赞
    private PopupWindow popupWindow;
    private TextView mViewBottom;
    private View popView;
    private BaseDataBean<PersonBean> personBeanBaseDataBean;
    private String imagePath;
    private RelativeLayout mRlHeader;
    private String back;
    private View statusMineView;

    @Override
    protected void initView() {
        personCenterPresenter = new PersonCenterPresenter(this);
        statusMineView=rootView.findViewById(R.id.home_status_view);
        nickname = rootView.findViewById(R.id.user_name);
        mRlHeader = rootView.findViewById(R.id.head_layout);
        userinfo = rootView.findViewById(R.id.user_info);
        sign = rootView.findViewById(R.id.user_introduce);
        accountId = rootView.findViewById(R.id.id_account);
        lableImg = rootView.findViewById(R.id.arrow);
        label1 = rootView.findViewById(R.id.id_lable1);
        label2 = rootView.findViewById(R.id.id_lable2);
        attent = rootView.findViewById(R.id.attent);
        messageBg = rootView.findViewById(R.id.message_bg);
        headView = rootView.findViewById(R.id.header_image);
        headView.setDrawingCacheEnabled(true);
        countAttent = rootView.findViewById(R.id.count_attend);
        countFans = rootView.findViewById(R.id.count_fans);
        countPraise = rootView.findViewById(R.id.count_praise);
        mViewBottom = rootView.findViewById(R.id.view_bottom);
        if (NotchUtil.isAllScreenDevice(getActivity())){
            statusMineView.setVisibility(View.VISIBLE);
        }else{
            statusMineView.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(other)) {
            minTopMargin = getResources().getDimensionPixelSize(R.dimen.dp_50);
            mFlexibleSpaceHeight = getResources().getDimensionPixelSize(R.dimen.dp_333);
        }else{
            mFlexibleSpaceHeight = getResources().getDimensionPixelSize(R.dimen.dp_250);
            minTopMargin = getResources().getDimensionPixelSize(R.dimen.dp_40);
        }
        topActionBar = rootView.findViewById(R.id.topbar);
//        topActionBar.showButtonImage(R.drawable.icon_setting, TopActionBar.RIGHT_AREA);
        topActionBar.setButtonClickListener(this);
        mPager = (ViewPager) rootView.findViewById(R.id.pager);
        mSlidingTabLayout = (SlidingTabLayout) rootView.findViewById(R.id.sliding_tabs);
        dialog = new BottomListDialog(getContext());
        initPopup();
        onInitListener();
        ObserverManager.getInstance().add(this);
        if (!TextUtils.isEmpty(other)) {
            refreshData();
        }
        BroadcastManager.getInstance(getContext()).addAction(Constant.REFRESH, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (mPagerAdapter==null || mPagerAdapter.fragmentList==null || mPagerAdapter.fragmentList.size()<=0) return;
                for (int i = 0; i < mPagerAdapter.fragmentList.size(); i++) {
                    if (mPagerAdapter.fragmentList.get(i) instanceof PersonTabListVideoFragment) {
                        ((PersonTabListVideoFragment) mPagerAdapter.fragmentList.get(i)).setRefresh(true);
                    }
                    if (mPagerAdapter.fragmentList.get(i) instanceof PersonTabListParaGraphFragment) {
                        ((PersonTabListParaGraphFragment) mPagerAdapter.fragmentList.get(i)).setRefresh(true);
                    }
                }
                if (isAdded()) {
                    getData();
                }else{
                    mPagerAdapter.notifyDataSetChanged();
                }
            }
        });
    }
    /**
     * 数据刷新
     */
    public void refreshData() {
        BroadcastManager.getInstance(getContext()).addAction(Constant.BACK, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                back = intent.getStringExtra("result");
            }
        });
        if (!TextUtils.isEmpty(back)){
            initBroad();
            return;
        }
        getData();
    }
    void initBroad(){
        back ="";
    }
    void getData(){
        if (currentId == 0 || currentPosition == 4) {
            currentId = LogonUtils.getProFildId();
        }
        checkState();
        personCenterPresenter.getPersonInfo(currentId);
    }

    public void goneButtomView(int isGone) {
        if (mViewBottom != null) {
            mViewBottom.setVisibility(isGone);
        }
    }

    public boolean isNeedFresh = false;

    @Override
    public void onResume() {
        super.onResume();
        if (isOutLogon) {
            ((MainActivity) getActivity()).goHomeFragment();
            isOutLogon = false;
            currentId = 0;
            isNeedFresh = true;
            return;
        }
        if (currentId == 0) {
            goneButtomView(View.VISIBLE);
        } else {
            goneButtomView(View.GONE);
        }
        LogUtils.e("HomeSettingFragmentonResume" + isNeedFresh);
        //粉丝列表，关注列表，登录，修改信息，发布段子回来需要更新页面
        if (getUserVisibleHint()) {
            refreshData();
        }


    }

    /**
     * 判断是自己的主页还是其他人的
     */
    private void checkState() {
        topActionBar.setButtGone(RIGHT_AREA2);
        if (currentId == LogonUtils.getProFildId()) {//个人主页面
            attent.setVisibility(View.GONE);
            messageBg.setVisibility(View.GONE);
            topActionBar.setTitle("我的");
            topActionBar.showIvDian();
            lableImg.setVisibility(View.VISIBLE);
            topActionBar.showButtonImage(R.drawable.more_icon, R.mipmap.icon_cosfun_msg, R.drawable.more_icon);
            if (1 != tag) {
                topActionBar.showButtonImage(0, TopActionBar.LEFT_AREA);
                if (!TextUtils.isEmpty(other)) {
                    topActionBar.setPadding(0, getResources().getDimensionPixelSize(R.dimen.dp_18), 0, 0);
                }
                mTabHeight = getResources().getDimensionPixelSize(R.dimen.dp_75);
                mFlexibleSpaceHeight = getResources().getDimensionPixelSize(R.dimen.dp_333);
                minTopMargin = getResources().getDimensionPixelSize(R.dimen.dp_50);

            } else {
                mRlHeader.setPadding(0, getResources().getDimensionPixelSize(R.dimen.dp_5), 0, 0);
                topActionBar.showButtonImage(R.drawable.back_big_icon, TopActionBar.LEFT_AREA);
                mFlexibleSpaceHeight = getResources().getDimensionPixelSize(R.dimen.dp_308);
                mTabHeight = getResources().getDimensionPixelSize(R.dimen.dp_60);
                minTopMargin = getResources().getDimensionPixelSize(R.dimen.dp_45);
            }
            if (isNeedSmooth){
                topActionBar.showButtonImage(R.drawable.back_big_icon, TopActionBar.LEFT_AREA);
            }
        } else {
            attent.setVisibility(View.VISIBLE);
            messageBg.setVisibility(View.VISIBLE);
            lableImg.setVisibility(View.GONE);
            topActionBar.setTitle("TA的主页");
            topActionBar.showButtonImage(R.drawable.more_icon,RIGHT_AREA);
            topActionBar.setGoneIv();
            if (1 == tag) {
                mRlHeader.setPadding(0, getResources().getDimensionPixelSize(R.dimen.dp_5), 0, 0);
                mFlexibleSpaceHeight = getResources().getDimensionPixelSize(R.dimen.dp_308);
                mTabHeight = getResources().getDimensionPixelSize(R.dimen.dp_60);
                minTopMargin = getResources().getDimensionPixelSize(R.dimen.dp_45);
            }
            topActionBar.showButtonImage(R.drawable.back_big_icon, TopActionBar.LEFT_AREA);
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        LogUtils.e(TAG, "hidden ==========>" + hidden);
        if (!hidden) {
            refreshData();
        }
    }

    private void initPopup() {
        popView = LayoutInflater.from(getContext()).inflate(R.layout.pop_pull_black, null);
        TextView tv_cancle = popView.findViewById(R.id.tv_cancle);
        TextView tv_pull_black = popView.findViewById(R.id.tv_pull_black);
        tv_cancle.setOnClickListener(this);
        tv_pull_black.setOnClickListener(this);
        popupWindow = new PopupWindow(getContext());
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setContentView(popView);
    }


    /**
     * 绑定监听
     */
    private void onInitListener() {
        attent.setOnClickListener(this);
        headView.setOnClickListener(this);
        messageBg.setOnClickListener(this);
        countAttent.setOnClickListener(this);
        countFans.setOnClickListener(this);
        countPraise.setOnClickListener(this);
        lableImg.setOnClickListener(this);
        label1.setOnClickListener(this);
        label2.setOnClickListener(this);
        mRlHeader.setOnClickListener(this);
        ScrollUtils.addOnGlobalLayoutListener(mSlidingTabLayout, new Runnable() {
            @Override
            public void run() {
                translateTab(0, false);
            }
        });
        dialog.setOnClickBottomListListener(new BottomListDialog.OnClickBottomListListener() {
            @Override
            public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
                if (personBeanBaseDataBean == null || personBeanBaseDataBean.data == null) {
                    return;
                }
                switch (list.get(position)) {
                    case "分享个人名片":
                        ShareFragment shareFragment = ShareFragment.newInstance();
                        shareFragment.setHomeCopy(true);
                        shareFragment.setLisenter(new ShareFragment.OnShareItemClickLisenter() {
                            @Override
                            public void share(SHARE_MEDIA share_media, int type) {
                                ShareUtils.getIntance().sharePerson(getActivity(), share_media, String.valueOf(currentId), ShareUtils.sharePersonCardStart + personBeanBaseDataBean.getData().profile.nickName + ShareUtils.sharePersonCardEnd, ShareUtils.sharePersonCardDes, personBeanBaseDataBean.getData().profile.image, new ShareUtils.ShareListener() {
                                    @Override
                                    public void onShareFinish() {
                                        hideLoading();
                                    }

                                    @Override
                                    public void onShareSuccess() {

                                    }
                                });
                            }

                            @Override
                            public void other(int type) {

                            }
                        });
                        shareFragment.show(getActivity().getSupportFragmentManager(), "myFragment");
                        shareFragment.setTag("play");
                        dialog.dissMiss();
                        break;
                    case "举报":
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", 2);
                        bundle.putInt("workId", currentId);
                        TerminalActivity.showFragment(getContext(), MessageReportFragment.class, bundle);
                        dialog.dissMiss();
                        break;
                    case "拉黑":
                        if (popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                        popupWindow.showAtLocation(popView, Gravity.CENTER, 0, 0);
//                        personCenterPresenter.getPullBlack(user_id);
                        dialog.dissMiss();
                        break;
                    case "取消拉黑":
                        personCenterPresenter.getCancelPullBlack(currentId);
                        dialog.dissMiss();
                        break;

                    case "编辑资料":
                        TerminalActivity.showFragment(getContext(), PersonInfoFragment.class, null);
                        break;
                    case "设置":
                        TerminalActivity.showFragment(getContext(), HomeSettingFragment.class, null);
                        break;
                    case "拍照":
                        ImageViewUtils.starShoot(HomeMineFragment.this, true);
                        break;
                    case "从相册选择":
                        ImageViewUtils.starShoot(HomeMineFragment.this, false);
                        break;
                }
            }

            @Override
            public void onClickBottom() {
                dialog.dissMiss();
            }
        });
    }

    void showDialog() {
        if (currentId == LogonUtils.getProFildId()) {//个人主页面
//                    TerminalActivity.showFragment(getContext(), HomeSettingFragment.class, null);
            if (dialog == null) dialog = new BottomListDialog(getContext());
            if (mList == null) mList = new ArrayList<>();
            mList.clear();
            mList.add("分享个人名片");
            mList.add("编辑资料");
            mList.add("设置");
            dialog.setList(mList);
            dialog.show();
        } else {
            personCenterPresenter.getReadPullBlackState(currentId);

        }
    }

    @Override
    protected void getBundle(Bundle bundle) {
        currentId = bundle.getInt("user_id");
        tag = bundle.getInt("tag");
//        other = bundle.getString(Constant.OTHER);
    }


    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_mine_layout;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_layout:
                if (currentId == LogonUtils.getProFildId()) {//是自己的主页的时候,点击更换头像
                    TerminalActivity.showFragment(getContext(), PersonInfoFragment.class, null);
                }
                break;
            case R.id.header_image:
                if (currentId == LogonUtils.getProFildId()) {//是自己的主页的时候,点击更换头像
                    if (dialog == null) dialog = new BottomListDialog(getContext());
                    if (mList == null) mList = new ArrayList<>();
                    mList.clear();
                    mList.add("从相册选择");
                    mList.add("拍照");
                    dialog.setList(mList);
                    dialog.show();
                } else {//否则,点击看大图
                    if (TextUtils.isEmpty(headurl)) {
                        AppUtils.showHintDialogToast(getActivity(), "TA还没有设置头像呦!");
                        return;
                    }
                    ImageViewUtils.previewImage(getActivity(), headurl);
                }
                break;
            case R.id.count_praise://获赞列表
                showFavor();
                break;
            case R.id.count_fans://粉丝列表
                Bundle bundle1 = new Bundle();
                bundle1.putInt(AttentListFragment.FLAG, 1);
                bundle1.putInt(AttentListFragment.ID, currentId);
                isNeedFresh = true;
                TerminalActivity.showFragment(getActivity(), AttentListFragment.class, bundle1);
                break;
            case R.id.count_attend://关注列表
                Bundle bundle2 = new Bundle();
                bundle2.putInt(AttentListFragment.FLAG, 2);
                bundle2.putInt(AttentListFragment.ID, currentId);
                TerminalActivity.showFragment(getActivity(), AttentListFragment.class, bundle2);
                break;

            case R.id.arrow: //
            case R.id.id_lable1: //
            case R.id.id_lable2: //
                Bundle bundle = new Bundle();
                bundle.putLong(USERID, currentId);
                TerminalActivity.showFragment(getActivity(), LableDetailFragment.class, bundle);
                break;
            case R.id.message_bg: //发送消息
                if (LogonUtils.checkLogon(getActivity(), false, 4)) {
                    Navigate.startMessageNotification(getActivity(), currentId, nickname.getText().toString());
                }
                break;
            case R.id.attent: //关注这个人
                if (LogonUtils.checkLogon(getActivity(), false, 4)) {
                    if ("关注".equals(attent.getText())) {
                        personCenterPresenter.loginFollowFans(currentId + "");
                    } else {
                        personCenterPresenter.loginNoFollow(currentId + "");
                    }
                }
                break;
            case R.id.tv_pull_black:
                personCenterPresenter.getPullBlack(currentId);
                popupWindow.dismiss();
                break;
            case R.id.tv_cancle:
                popupWindow.dismiss();
                break;

        }
    }

    /**
     *
     */
    public void showFavor() {
        if (TextUtils.isEmpty(favor)) {
            favor = "获赞数据异常";
        }
        final ConfirmDialog confirmDialog = new ConfirmDialog(getActivity(), favor);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                // TODO Auto-generated method stub
                confirmDialog.dismiss();

            }

        });
    }

    /**
     * @param scrollY scroll position of Scrollable
     * @param s       caller Scrollable view
     */
    public void onScrollChanged(int scrollY, Scrollable s) {
        if (null == mPagerAdapter) {
            return;
        }
        PersonTabBaseFragment fragment =
                (PersonTabBaseFragment) mPagerAdapter.getItemAt(mPager.getCurrentItem());
        if (fragment == null) {
            return;
        }
        View view = fragment.getView();
        if (view == null) {
            return;
        }
        Scrollable scrollable = (Scrollable) view.findViewById(R.id.scroll);
        if (scrollable == null) {
            return;
        }
        if (scrollable == s) {
            int adjustedScrollY = Math.min(scrollY, mFlexibleSpaceHeight - mTabHeight);
            translateTab(adjustedScrollY, false);
            propagateScroll(adjustedScrollY);
        }
    }

    private void translateTab(int scrollY, boolean animated) {
        int flexibleSpaceImageHeight = getResources().getDimensionPixelSize(R.dimen.dp_260);
        RelativeLayout imageView = rootView.findViewById(R.id.header_layout);

        int minOverlayTransitionY = mTabHeight - flexibleSpaceImageHeight;
        ViewHelper.setTranslationY(imageView, ScrollUtils.getFloat(-scrollY, minOverlayTransitionY, 0));

        ViewPropertyAnimator.animate(mSlidingTabLayout).cancel();
        float translationY = ScrollUtils.getFloat(-scrollY + mFlexibleSpaceHeight - mTabHeight, minTopMargin, mFlexibleSpaceHeight - mTabHeight);
        if (animated) {
            ViewPropertyAnimator.animate(mSlidingTabLayout)
                    .translationY(translationY)
                    .setDuration(200)
                    .start();
        } else {
            ViewHelper.setTranslationY(mSlidingTabLayout, translationY);
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void setPivotXToTitle(View view) {
        final TextView mTitleView = (TextView) view.findViewById(R.id.title);
        Configuration config = getResources().getConfiguration();
        if (Build.VERSION_CODES.JELLY_BEAN_MR1 <= Build.VERSION.SDK_INT
                && config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
            ViewHelper.setPivotX(mTitleView, view.findViewById(android.R.id.content).getWidth());
        } else {
            ViewHelper.setPivotX(mTitleView, 0);
        }
    }

    private void propagateScroll(int scrollY) {
        mPagerAdapter.setScrollY(scrollY);
        for (int i = 0; i < mPagerAdapter.getCount(); i++) {
            // Skip current item
            if (i == mPager.getCurrentItem()) {
                continue;
            }

            PersonTabBaseFragment f =
                    (PersonTabBaseFragment) mPagerAdapter.getItemAt(i);
            if (f == null) {
                continue;
            }

            View view = f.getView();
            if (view == null) {
                continue;
            }
            f.setScrollY(scrollY, mFlexibleSpaceHeight);
            f.updateFlexibleSpace(scrollY);
        }
    }

    private String favor;

    @Override
    public void showLogonResult(BaseDataBean<PersonBean> personBeanBaseDataBean) {
        if (personBeanBaseDataBean == null || personBeanBaseDataBean.data == null) {
            return;
        }
        this.personBeanBaseDataBean = personBeanBaseDataBean;
        int[] nums = new int[4];
        nums[0] = (personBeanBaseDataBean.data.countVideo);
        nums[1] = personBeanBaseDataBean.data.countVideoFavor;
        nums[2] = personBeanBaseDataBean.data.countParagraph;
        nums[3] = personBeanBaseDataBean.data.countParagraphFavor;

        if (!isAdded()) {
            return;
        }
//        if (mPagerAdapter == null) {
            mPagerAdapter = new NavigationAdapter(getChildFragmentManager(), nums);
            mPager.setOffscreenPageLimit(1);
            mPager.setAdapter(mPagerAdapter);
            mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
            mSlidingTabLayout.setDistributeEvenly(true);
            mSlidingTabLayout.setViewPager(mPager);
//        }
        mPagerAdapter.setTitles(nums, currentId);
//        ((PersonTabListVideoFragment) mPagerAdapter.fragmentList.get(0)).refreshData(currentId);
        mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                translateTab(0, false);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        String mFavor = StringUtils.formatZanCount(personBeanBaseDataBean.data.countParagraphFavor + personBeanBaseDataBean.data.countVideoFavored);
        String mcountFans = StringUtils.formatZanCount(personBeanBaseDataBean.data.countFans);
        String mCountFollow = StringUtils.formatZanCount(personBeanBaseDataBean.data.countFollow);
        countPraise.setText(mFavor + " 获赞");

        countFans.setText(mcountFans + " 粉丝");
        countAttent.setText(mCountFollow + " 关注");
        PersonBean.PersonData data = personBeanBaseDataBean.data.profile;
        if (data == null) return;

        if (currentId == LogonUtils.getProFildId()) {//如果是自己得昵称，保存给其他地方使用
            LogonUtils.setNickName(TextUtils.isEmpty(data.nickName) ? "" : data.nickName);
        }
        String url = SPUtils.init().getString("headUrl");
        if (TextUtils.isEmpty(url)) {
            if (!TextUtils.isEmpty(data.image)) { //头像
                headurl = data.image;
                ImageUtils.LoadImage(getContext(),  data.image,headView,R.drawable.avatar_pic);
                if (currentId == LogonUtils.getProFildId()) {//如果是自己得头像，保存给其他地方使用
                    LogonUtils.setNickIcon(headurl);
                }
            } else {
                headView.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.avatar_pic));
                LogonUtils.setNickIcon("");
            }
        }else {
            headurl =url;
            ImageUtils.LoadImage(getContext(),  headurl,headView,R.drawable.avatar_pic);
            if (currentId == LogonUtils.getProFildId()) {//如果是自己得头像，保存给其他地方使用
                LogonUtils.setNickIcon(headurl);
            }
        }

        if (!TextUtils.isEmpty(data.nickName)) {
            nickname.setText(data.nickName);
        } else {
            nickname.setText("");
        }
        if (!TextUtils.isEmpty(data.id)) {
            accountId.setText("ID " + data.id);
        }

        switch (personBeanBaseDataBean.data.followType) {
            case 0:
                attent.setText("关注");
                break;
            case 1:
                backListener(currentId+"::1");
                attent.setText("已关注");
                break;
            case 2:
                backListener(currentId+"::1");
                attent.setText("互相关注");
                break;
            case -1:
                attent.setText("");
                break;
        }

        String sex = "";
        favor = "获得" + (personBeanBaseDataBean.data.countParagraphFavor + personBeanBaseDataBean.data.countVideoFavored) + "个赞";
        switch (data.sex) { //1男2女3不确定4保密
            case 1:
                sex = "小姐姐";
                favor = sex + favor;
                break;
            case 2:
                sex = "小哥哥";
                favor = sex + favor;
                break;
            case 3:
                sex = "不确定";
                break;
            case 4:
                sex = "保密";
                break;
            default:
                sex = "未填写";
                break;
        }
        if (!TextUtils.isEmpty(data.signature)) {
            sign.setText(data.signature);
        } else {
            sign.setText("这家伙很懒,还没有写签名");
        }
        if (personBeanBaseDataBean.data.userTag != null) {
            LabelBean labelBean = personBeanBaseDataBean.data.userTag;
            List<LabelBean.Label> labelList = new ArrayList<>();
            LabelBean.Label la1 = new LabelBean.Label(labelBean.actorTag, "演员");
            LabelBean.Label la2 = new LabelBean.Label(labelBean.audienceTag, "观众");
            LabelBean.Label la3 = new LabelBean.Label(labelBean.commentTag, "评论");
            LabelBean.Label la4 = new LabelBean.Label(labelBean.directorTag, "导演");
            LabelBean.Label la5 = new LabelBean.Label(labelBean.screenwriterTag, "编剧");
            labelList.add(la1);
            labelList.add(la2);
            labelList.add(la3);
            labelList.add(la4);
            labelList.add(la5);
            array(labelList);
            Log.i("zhikuan", labelList.toString());
            if (labelList.get(4).value == 0) {//全为0
                label1.setText("群众演员");
                label2.setText("路过乡亲");
            } else {
                label1.setText(getLabel(labelList.get(4).key, (int) labelList.get(4).value));
                label2.setText(getLabel(labelList.get(3).key, (int) labelList.get(3).value));
            }
        }
        String area ="";
        String userInfo = "";
        if (!TextUtils.isEmpty(data.areaid)&& !"0" .equals(data.areaid)) {
            area = AppUtils.getCityName(getContext(), data.areaid);
        }
        int birth= 0;
        if (0!=data.birthday){
            birth = DateUtils.getAge(data.birthday);
            userInfo = birth + "岁 | "  + sex;
        }

        if (!TextUtils.isEmpty(area)){
            if (0==birth) {
                userInfo = area + " | " + sex;
            }else{
                userInfo = birth + "岁 | " + area + " | " + sex;
            }
        }
        userinfo.setText(userInfo);

    }
    private void backListener(String back){
        AppListener.OnFocusBackListener backListener = AppListener.getInstance().getFocusBackListener();
        if (null !=backListener){
            backListener.onFocusBack(back);
        }
    }
    private String getLabel(String key, int value) {
        String label = "";
        switch (key) {
            case "演员":
                switch (value) {
                    default:
                        label = "群众演员";
                        break;
                    case 1:
                        label = "三线明星";
                        break;

                    case 2:
                        label = "一线大咖";
                        break;
                    case 3:
                        label = "资深戏骨";
                        break;
                }
                break;
            case "观众":
                switch (value) {
                    default:
                        label = "路过相亲";
                        break;
                    case 1:
                        label = "常年围观";
                        break;

                    case 2:
                        label = "阅遍世事";
                        break;
                    case 3:
                        label = "上帝之眼";
                        break;
                }
                break;
            case "评论":
                switch (value) {
                    default:
                        label = "守口如瓶";
                        break;
                    case 1:
                        label = "偶尔灌水";
                        break;

                    case 2:
                        label = "能说会道";
                        break;
                    case 3:
                        label = "道破天机";
                        break;
                }
                break;
            case "导演":
                switch (value) {
                    default:
                        label = "实习导演";
                        break;
                    case 1:
                        label = "拍拍小片";
                        break;

                    case 2:
                        label = "金牌导演";
                        break;
                    case 3:
                        label = "大师导演";
                        break;
                }
                break;
            case "编剧":
                switch (value) {
                    default:
                        label = "新人写手";
                        break;
                    case 1:
                        label = "出手成章";
                        break;

                    case 2:
                        label = "摄人心魂";
                        break;
                    case 3:
                        label = "万古流芳";
                        break;
                }
                break;
        }
        return label;
    }

    public void array(List<LabelBean.Label> arr) {
        for (int i = 0; i < arr.size() - 1; i++) {//外层循环控制排序趟数
            for (int j = 0; j < arr.size() - 1 - i; j++) {//内层循环控制每一趟排序多少次
                if (arr.get(j).value > arr.get(j + 1).value) {
                    LabelBean.Label temp = arr.get(j);
                    arr.set(j, arr.get(j + 1));
                    arr.set(j + 1, temp);
                }
            }
        }
    }


    @Override
    public void showReadPullBlackStateResult(int status) {
        if (dialog == null)
            dialog = new BottomListDialog(getContext());
        if (mList == null)
            mList = new ArrayList<>();
        mList.clear();
        if (status == -1) {
            mList.clear();
            mList.add("分享个人名片");
            mList.add("举报");
            mList.add("拉黑");
        } else {
            mList.clear();
            mList.add("分享个人名片");
            mList.add("举报");
            mList.add("取消拉黑");
        }
        dialog.setList(mList);
        dialog.show();
    }

    @Override
    public void showPullBlackResult(int data) {
        if (data == 1) {
            showToast("拉黑用户成功！");
            mList.clear();
            mList.add("分享个人名片");
            mList.add("举报");
            mList.add("取消拉黑");
            dialog.setList(mList);
        }
    }

    @Override
    public void showCancelPullBlack(int data) {
        if (data == 1) {
            showToast(getResources().getString(R.string.cancel_black_success));
            mList.clear();
            mList.add("分享个人名片");
            mList.add("举报");
            mList.add("拉黑");
            dialog.setList(mList);
        }
    }

    @Override
    public void getFollowResult(FollowBean followBean) {
        backListener(currentId+"::1");
        if (null == followBean) {
            return;
        }
        if (followBean.getRelationShip() == null) {
            return;
        }
        attent.setText(followBean.getRelationShip());
    }
//    void onFocus(String focus){
//        AppListener.OnFocusBackListener onFocusBackListener = AppListener.getInstance().getOnFocusBackListener();
//        if (null != onFocusBackListener){
//            onFocusBackListener.onFocus(focus);
//        }
//    }
    @Override
    public void getNoFollowResult(FollowBean followBean) {
        backListener(currentId+"::2");
        if (null == followBean) {
            return;
        }
        if (followBean.getRelationShip() == null) {
            return;
        }
        attent.setText(followBean.getRelationShip());
    }

    @Override
    public void showLoading(String msg) {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        hideLoadingDialog();
    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }


    private boolean isChangeId = true;
    private boolean isNeedSmooth = false;//标记滑动过来的
    private int currentPosition = 0;

    /**
     * 标记添加到那个tab
     *
     * @param i
     */
    public void setCurrentPosition(int i) {
        currentPosition = i;
    }

    public int getCurrentPosition() {
        return currentPosition;
    }

    public boolean getNeedSmooth() {
        return isNeedSmooth && !(LogonUtils.getProFildId() == currentId);
    }

    public void setIsChange(boolean b) {
        isChangeId = b;
    }

    @Override
    public void observerUpData(int eventType, int index, int id) {
        if (eventType == ObserverListener.EVENT_CHANGE_OPUS && isChangeId) {
            topActionBar.showLeftButton(true);
            currentId = id;
            isNeedSmooth = true;
            LogUtils.e("changeId", " observerUpData=" + currentId);
        }

    }

    @Override
    public void onLeftButtonClick(View view) {
        if (!isNeedSmooth) {//表示不是左滑进来的
            getActivity().finish();
            return;
        }
        if (backLisenter != null) {
            backLisenter.back();//左滑调用viewpager
            return;
        }
        getActivity().finish();
    }

    @Override
    public void onRightButton2Click(View view) {
        topActionBar.setGoneIv();
        TerminalActivity.showFragment(getActivity(), MessageFragment.class, null);
    }

    @Override
    public void onRightButtonClick(View view) {
        showDialog();
    }

    private class NavigationAdapter extends CacheFragmentStatePagerAdapter {

        private List<PersonTabBaseFragment> fragmentList = new ArrayList<>();
        private int[] TITLES;
        private int userId;
        private int mScrollY;

        /**
         * 更新tab数量
         * @param titles
         * @param id
         */
        public void setTitles(int[] titles, int id) {
            if (titles == null || titles.length != 4 && TITLES == null || TITLES.length != 4) {
                return;
            }
            boolean noFresh = titles[0] == TITLES[0] && titles[1] == TITLES[1]
                    && titles[2] == TITLES[2] && titles[3] == TITLES[3];

            if (mSlidingTabLayout != null) {
                mSlidingTabLayout.updateTabView();
            }
            if (!noFresh || userId != id) {
                for (int i = 0; i < fragmentList.size(); i++) {
                    if (fragmentList.get(i) instanceof PersonTabListVideoFragment) {
                        ((PersonTabListVideoFragment) fragmentList.get(i)).refreshData(currentId);
                    }
                    if (fragmentList.get(i) instanceof PersonTabListParaGraphFragment) {
                        ((PersonTabListParaGraphFragment) fragmentList.get(i)).refreshData(currentId);
                    }
                }
            }
            TITLES = titles;
            userId = id;
        }

        public NavigationAdapter(FragmentManager fm, int[] titles) {
            super(fm);
            userId = currentId;
            TITLES = titles;
            PersonTabBaseFragment f0 = new PersonTabListVideoFragment();
            f0.setArguments(mScrollY, "1", currentId);
            PersonTabBaseFragment f1 = new PersonTabListVideoFragment();
            f1.setArguments(mScrollY, "2", currentId);

            PersonTabListParaGraphFragment f2 = new PersonTabListParaGraphFragment();
            f2.setArguments(mScrollY, "1", currentId);
            PersonTabListParaGraphFragment f3 = new PersonTabListParaGraphFragment();
            f3.setArguments(mScrollY, "2", currentId);

            fragmentList.add(f0);
            fragmentList.add(f1);
            fragmentList.add(f2);
            fragmentList.add(f3);

        }

        public void setScrollY(int scrollY) {
            mScrollY = scrollY;
        }

        @Override
        protected Fragment createItem(int position) {
            PersonTabBaseFragment f;
            final int pattern = position % 4;
            if (fragmentList != null && fragmentList.size() > pattern) {
                return fragmentList.get(position);
            }
            switch (pattern) {
                case 0: {
                    f = new PersonTabListVideoFragment();
                    f.setArguments(mScrollY, "1", currentId);
                    break;
                }
                case 1: {
                    f = new PersonTabListVideoFragment();
                    f.setArguments(mScrollY, "2", currentId);
                    break;
                }
                case 2: {
                    f = new PersonTabListParaGraphFragment();
                    f.setArguments(mScrollY, "1", currentId);
                    break;
                }
                case 3:
                default: {
                    f = new PersonTabListParaGraphFragment();
                    f.setArguments(mScrollY, "2", currentId);
                    break;
                }
            }
            return f;
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            String[] tabs = new String[4];
            tabs[0] = personBeanBaseDataBean.data.countVideo + ", 作品";
            tabs[1] = personBeanBaseDataBean.data.countVideoFavor + ", 喜欢的作品";
            tabs[2] = personBeanBaseDataBean.data.countParagraph + ", 便当";
            tabs[3] = personBeanBaseDataBean.data.countParagraphFavor + ", 喜欢的便当";
            return tabs[position];
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    LocalMedia localMedia = selectList.get(0);
                    if (localMedia.isCut()) {
                        imagePath = localMedia.getCutPath();
                    } else if (localMedia.isCompressed()) {
                        imagePath = localMedia.getCompressPath();
                    } else {
                        imagePath = localMedia.getPath();
                    }
                    headurl = imagePath;
                    SPUtils.init().putString("headUrl", headurl);
                    Glide.with(this).load(new File(headurl)).into(headView);
                    isNeedFresh = false;
                    break;
            }
        }
    }

    BackLisenter backLisenter = null;

    public void setBackLisenter(BackLisenter backLisenter) {
        this.backLisenter = backLisenter;
    }

    public interface BackLisenter {
        void back();
    }

    public boolean onBack() {
        if (backLisenter != null) {
            backLisenter.back();
        }
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BroadcastManager.getInstance(getContext()).destroy(Constant.REFRESH);
    }
}
